//
//  SendFriendCircleViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2017/11/20.
//  Copyright © 2017年 史宵宵. All rights reserved.
//

#import "SendFriendCircleViewController.h"
#import "TZImagePickerController.h"
#import "WhoScanViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "THDatePickerView.h"
#import "XHStarRateView.h"

@interface SendFriendCircleViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate,UITextViewDelegate,THDatePickerViewDelegate,XHStarRateViewDelegate>
@property (nonatomic,weak) JSTextView *releaseContentTextView;  //发布的评论
@property (nonatomic,copy) NSString *contentStr; //内容
@property (nonatomic,strong) NSMutableArray *imageDataArray; //图片数组
@property (nonatomic,strong) NSArray *whoScanTextArray; //谁可以看的范围 0：所有人 1仅自己 2 老师 3 学生 4家长
@property (nonatomic,copy) NSString *whoScanSelectId; //选中 看的范围 的数字
@property (nonatomic,copy) NSString *selectTextStr;//选中 看的范围 的文字

@property (weak, nonatomic) THDatePickerView *dateView;
@property (nonatomic,copy) NSString *remindTimeStr;//提醒的时间
@property(nonatomic,weak) XHStarRateView *starView; //选星级
@property (nonatomic,weak) UILabel *desLabel;//评价的形容
@property (nonatomic,weak) UILabel *scoreLabel;//显示分数

@property (nonatomic,strong) NSArray *coreArray;//描述分数的array

@property (nonatomic,assign) BOOL isEdit;
@property (nonatomic,assign) BOOL isSending;
@end

@implementation SendFriendCircleViewController
- (NSMutableArray *)imageDataArray{
    if (!_imageDataArray) {
        _imageDataArray = [NSMutableArray array];
    }
    return _imageDataArray;
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    
    return UIStatusBarStyleLightContent;
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    //    [Global setStatusBarBackgroundColor:[UIColor clearColor]];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.titleStr;
    self.isSending = NO;
    self.whoScanTextArray = @[@"所有人", @"仅自己", @"老师", @"学生", @"家长"];
    self.whoScanSelectId = @"0";
    self.coreArray = @[@"一般", @"还不错", @"好", @"很好", @"非常好"];
    
    if (self.sendType == KSendAdviceToParents ) {
        MyLog(@"%@",[JHUserInfo getUserInfo].role_name);
        if ([[JHUserInfo getUserInfo].role_type isEqualToString:@"2"]||[[JHUserInfo getUserInfo].role_type isEqualToString:@"3"]||[[JHUserInfo getUserInfo].role_type isEqualToString:@"4"]) {
            self.navigationItem.rightBarButtonItem = [UIBarButtonItem leftBarButtonItemWithTitle:@"修改" target:self selector:@selector(editResultInput)];
        }
        self.isEdit = NO;
    }else if (self.sendType == KSendTermGoals ){
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithTitle:@"发送" target:self selector:@selector(sendTermGoals)];
        self.isEdit = YES;
    }
    else{
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithTitle:@"发送" target:self selector:@selector(send)];
        self.isEdit = YES;
    }
}
#pragma mark - 修改成绩
- (void)editResultInput{
    self.isEdit = YES;
    [self.tableView reloadData];
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.sendType == KSendMoodDiary || self.sendType == KSendHomeWork || self.sendType == KSendTermGoals) {
        return 1;
    }
    return 2;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 1){
        return 1;
    }
    if (self.sendType == KSendTermGoals || self.sendType == KSendAdviceToParents) {
        return 1;
    }
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!indexPath.section && !indexPath.row) {
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell00"];
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        JSTextView *releaseContentTextView = [[JSTextView alloc] initWithFrame:CGRectMake(10, 10, kScreenW - 20, 80)];
        releaseContentTextView.font = [UIFont systemFontOfSize:16];
        releaseContentTextView.textColor = KTEXTMAINCOLOR;
        releaseContentTextView.delegate = self;
        releaseContentTextView.autocorrectionType = UITextAutocorrectionTypeNo;  //取消纠错
        releaseContentTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;  //取消首字母大写
        releaseContentTextView.returnKeyType = UIReturnKeyDefault;  //return改成done
        releaseContentTextView.myPlaceholder = strIsEmpty(self.placeholderStr)? @"这一刻想说点什么......" : self.placeholderStr;
        [cell.contentView addSubview:releaseContentTextView];
        releaseContentTextView.text = strIsEmpty(self.sureContentStr)?@"":self.sureContentStr;
        releaseContentTextView.userInteractionEnabled = self.isEdit;
        self.releaseContentTextView = releaseContentTextView;
        return cell;

    }else if (indexPath.section == 0 && indexPath.row == 1){
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell01"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        double margin = 15;
        double imageWidth = (kScreenW - margin*4)/3;
        for (NSInteger i=0; i < _imageDataArray.count; i++)
        {
            double x = (i%3)*(margin+imageWidth)+margin;
            double y = 15 + (i/3) * (imageWidth+15);
            double x1 = (i%4)*(margin+imageWidth)+imageWidth+margin - 15;
            double y1 = 0 + (i/3) * (imageWidth+15);
            
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, imageWidth, imageWidth)];
            imageView.image = _imageDataArray[i];
            imageView.backgroundColor = [UIColor clearColor];
            imageView.userInteractionEnabled = YES;
            [cell.contentView addSubview:imageView];
            
            UIImageView *cancelReleaseImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x1, y1, 20, 20)];
            cancelReleaseImageView.backgroundColor = [UIColor clearColor];
            cancelReleaseImageView.image = [UIImage imageNamed:@"cancelRelaseAddImage.png"];
            cancelReleaseImageView.tag = 2000 + i;
            [cancelReleaseImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelImageTap:)]];
            [cell.contentView addSubview:cancelReleaseImageView];
            cancelReleaseImageView.userInteractionEnabled = YES;
        }
        
        if (_imageDataArray.count < 9)
        {
            double x = (_imageDataArray.count %3)*(imageWidth+margin)+15;
            double y = 15 + (_imageDataArray.count/3) * (imageWidth+15);
            
            UIImageView *releaseImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, imageWidth, imageWidth)];
            releaseImageView.hidden = NO;
            releaseImageView.image = [UIImage imageNamed:@"Camera"];
            [releaseImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(realeaseAddImageTap)]];
            [cell.contentView addSubview:releaseImageView];
            releaseImageView.userInteractionEnabled = YES;
            //            releaseImageView.layer.cornerRadius = 30;
            //            releaseImageView.layer.masksToBounds = YES;
        }
        return cell;
    }else if(self.sendType == KSendAdviceToParents){
        static NSString *identifier = @"cell1";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor whiteColor];
//        }
        self.score = strIsEmpty(self.score)? @"5": self.score;
        NSInteger scoreInteger = (strIsEmpty(self.score) || [self.score isEqualToString:@"0"])? 5: [self.score integerValue];
        UILabel *desLabel = [[UILabel alloc]init];
        desLabel.text = self.coreArray[scoreInteger-1];
        desLabel.frame = CGRectMake(20, 50, [Global getSizeOfString:self.coreArray[1] maxWidth:kScreenW maxHeight:25 withFontSize:14].width + 20, 25);
        desLabel.textColor = [UIColor whiteColor];
        desLabel.backgroundColor = KBACKNAVIGATIONCOLOR;
        desLabel.textAlignment = NSTextAlignmentCenter;
        desLabel.clipsToBounds = YES;
        desLabel.font = [UIFont systemFontOfSize:14];
        desLabel.layer.cornerRadius = 10;
        [cell.contentView addSubview:desLabel];
        self.desLabel = desLabel;
        
        XHStarRateView *starRateView = [[XHStarRateView alloc]init];
        starRateView.isMove = self.isEdit;
        starRateView.rateStyle = WholeStar;
        starRateView.frame = CGRectMake(CGRectGetMaxX(desLabel.frame) + 10, 45, 150, 25);
        [starRateView setStarScore:self.score];
        starRateView.delegate = self;
        starRateView.isMove = self.isEdit;
        [cell.contentView addSubview:starRateView];
        self.starView = starRateView;
        
        UILabel *scoreLabel = [[UILabel alloc]init];
        scoreLabel.frame = CGRectMake(kScreenW - 100, 50, 80, 20);
        scoreLabel.textAlignment = NSTextAlignmentRight;
        scoreLabel.text = [NSString stringWithFormat:@"%@分",self.score];
        scoreLabel.textColor =  KMONEYCOLOR;
        [cell.contentView addSubview:scoreLabel];
        self.scoreLabel = scoreLabel;
        
        return cell;
    }
    else{
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell11"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        UIButton *whoScanButton = [[UIButton alloc]initWithFrame:CGRectMake( 10, 12, 100, 20)];
        if (self.sendType == KSendFriendCircle) {
            [whoScanButton setTitle:@" 谁可以看" forState:UIControlStateNormal];
            [whoScanButton setImage:[UIImage imageNamed:@"whoScan"] forState:UIControlStateNormal];
            [whoScanButton addTarget:self action:@selector(whoScan) forControlEvents:UIControlEventTouchUpInside];
            
            UILabel *label = [[UILabel alloc]init];
            label.frame = CGRectMake(kScreenW / 2, CGRectGetMinY(whoScanButton.frame), kScreenW / 2 - 10, 20);
            label.text = strIsEmpty(self.selectTextStr)? @"公开":self.selectTextStr;
            label.textAlignment = NSTextAlignmentRight;
            label.textColor = [UIColor darkGrayColor];
            label.font = [UIFont systemFontOfSize:14];
            [cell.contentView addSubview:label];
        }else if (self.sendType == KSendFutureMyself){
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            [whoScanButton setTitle:@" 提醒时间" forState:UIControlStateNormal];
            [whoScanButton setImage:[UIImage imageNamed:@"whoScan"] forState:UIControlStateNormal];
            cell.detailTextLabel.text = self.remindTimeStr;
        }
        [whoScanButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        whoScanButton.titleLabel.font = [UIFont systemFontOfSize:14];
        whoScanButton.titleLabel.textAlignment = NSTextAlignmentLeft;
        
        [cell.contentView addSubview:whoScanButton];
        return cell;
    }

}
#pragma mark - 选择星星
-(void)starRateView:(XHStarRateView *)starRateView currentScore:(CGFloat)currentScore{
    NSLog(@"%ld----  %f",starRateView.tag,currentScore);
    self.score = [NSString stringWithFormat:@"%.0f",currentScore];
    NSInteger score = [[NSString stringWithFormat:@"%.0f分",currentScore] intValue];
    self.desLabel.text = self.coreArray[score-1];
    self.desLabel.frame = CGRectMake(20, 50, [Global getSizeOfString:self.desLabel.text maxWidth:kScreenW maxHeight:25 withFontSize:14].width + 20, 25);
    self.starView.frame = CGRectMake(CGRectGetMaxX(self.desLabel.frame) + 10, 45, 150, 25);
    self.scoreLabel.text = [NSString stringWithFormat:@"%.0f分",currentScore];
    
}
#pragma mark - 跳转谁可以看页面
- (void)whoScan{
    WhoScanViewController *whoScanVC = [[WhoScanViewController alloc]init];
    __weak typeof (self)unself = self;
    whoScanVC.selectWhoScanBlock = ^(NSString *whoScanId) {
        unself.whoScanSelectId = whoScanId;
        
        NSArray *array = [whoScanId componentsSeparatedByString:@","];
        NSMutableArray *selectTextArray = [NSMutableArray array];
        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [selectTextArray addObject:self.whoScanTextArray[[obj integerValue]]];
        }];
        unself.selectTextStr = [selectTextArray componentsJoinedByString:@","];
        unself.whoScanSelectId = whoScanId;
        [unself.navigationController popViewControllerAnimated:YES];
        [unself.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
    };
    [self.navigationController pushViewController:whoScanVC animated:YES];
}
- (void)cancelImageTap:(UITapGestureRecognizer *)tap
{
    NSInteger index = tap.view.tag - 2000;
    [_imageDataArray removeObjectAtIndex:index];
    [self.tableView reloadData];
}

-(void)realeaseAddImageTap
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto){
        [self.imageDataArray addObjectsFromArray:photos];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:1 inSection:0], nil] withRowAnimation:UITableViewRowAnimationNone];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(self.sendType == KSendAdviceToParents && indexPath.section == 1){
        return 125;
    }else if (indexPath.section == 1) {
        return 44;
    }else if (indexPath.section == 0 && indexPath.row == 1) {
        if ((_imageDataArray.count + 1) <= 3)
        {
            return (kScreenW - 15*4)/3 + 30;
        }
        else if ((_imageDataArray.count + 1) <= 6)
        {
            return ((kScreenW - 15*4)/3) * 2 + 45;
        }else{
            return ((kScreenW - 15*4)/3) * 3 + 60;
        }
    }else{
        return 100;
    }

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    if (self.sendType == KSendAdviceToParents && section == 1) {
        view.frame = CGRectMake(0, 0, kScreenW, 44);
        view.backgroundColor = [UIColor whiteColor];
        
        UILabel *label = [[UILabel alloc]init];
        label.frame = CGRectMake(15, 12, kScreenW - 30, 20);
        label.text = @"您对孩子本月表现评分";
        [view addSubview:label];
    }else{
        view.frame = CGRectZero;
    }
    
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.sendType == KSendAdviceToParents && section == 1) {
        return 44.01f;
    }
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    if (section == 0) {
        view.frame = CGRectMake(0, 0, kScreenW, 5);
    }else if (self.sendType == KSendAdviceToParents) {
        view.frame = CGRectMake(0, kScreenH - 64 - 60, kScreenW, 60);
        view.backgroundColor = [UIColor whiteColor];
        
        UIButton *button = [[UIButton alloc]init];
        button.frame = CGRectMake(20, 5, kScreenW - 40, 50);
        [button setTitle:@"发给孩子" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        if (self.isEdit) {
            button.backgroundColor = KBACKNAVIGATIONCOLOR;
        }else{
            button.backgroundColor = [UIColor lightGrayColor];
        }
        button.userInteractionEnabled = self.isEdit;
        button.layer.cornerRadius = 5;
        [button addTarget:self action:@selector(sendAdviceToParents) forControlEvents:UIControlEventTouchUpInside];
        
        [view addSubview:button];
    }else{
        view.frame = CGRectZero;
    }
    
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 5.01f;
    }else if (self.sendType == KSendAdviceToParents) {
        return 60.01f;
    }
    return 0.01f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.sendType == KSendFutureMyself && indexPath.section == 1){
        MyLog(@"提醒时间");
        THDatePickerView *dateView = [[THDatePickerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 300, self.view.frame.size.width, 300)];
        dateView.delegate = self;
        dateView.title = @"请选择时间";
        [self.view addSubview:dateView];
        [dateView show];
        self.dateView = dateView;
//        self.dateView.frame = CGRectMake(0, self.view.frame.size.height - 300, self.view.frame.size.width, 300);
        
//        UIDatePicker *datePicker = [[UIDatePicker alloc]init];
//        datePicker.backgroundColor = [UIColor whiteColor];
//        datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh"];
//        datePicker.frame = CGRectMake(0, kScreenH - 200, kScreenW, 200);
//        datePicker.datePickerMode = UIDatePickerModeDateAndTime;
//        datePicker.minimumDate = [NSDate date];
//        [self.view addSubview:datePicker];
    }
}
#pragma mark ------键盘操作
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView == _releaseContentTextView)
    {
        self.contentStr = textView.text;
    }
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.releaseContentTextView resignFirstResponder];
    return YES;
}
#pragma mark - THDatePickerViewDelegate
/**
 保存按钮代理方法
 
 @param timer 选择的数据
 */
- (void)datePickerViewSaveBtnClickDelegate:(NSString *)timer {
    NSLog(@"保存点击");
    self.remindTimeStr = timer;
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
//    [UIView animateWithDuration:0.3 animations:^{
        self.dateView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 300);
//    }];
}

/**
 取消按钮代理方法
 */
- (void)datePickerViewCancelBtnClickDelegate {
    NSLog(@"取消点击");
   
//    [UIView animateWithDuration:0.3 animations:^{
        self.dateView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 300);
//    }];
}
#pragma mark - 发送帖子
- (void)send{
    [self.tableView endEditing:YES];
    if (self.isSending) {
        return;
    }
    self.isSending = YES;
    if (strIsEmpty(self.releaseContentTextView.text)) {
        [Global showActivityWithView:self.view withText:@"请输入看法"];
        return;
    }
    NSString *urlStr = [JSPathUtil urlAppFriendAddTopic];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
 
    if (self.sendType == KSendFriendCircle) {
        [dic setValue:self.whoScanSelectId forKey:@"whoCan"];   //谁可以看 0：所有人 1仅自己 2 老师 3 学生 4家长
        [dic setValue:@"1" forKey:@"topicType"]; //校友圈1
        [dic setValue:self.releaseContentTextView.text forKey:@"topicContext"];   //动态的内容详情
    }else if (self.sendType == KSendFutureMyself){
        if (strIsEmpty(self.remindTimeStr)) {
            [Global showActivityWithView:self.view withText:@"请选择日期"];
            return;
        }
        [dic setValue:@"3" forKey:@"topicType"];    //未来的自己3
        [dic setValue:[NSString stringWithFormat:@"%@:00",self.remindTimeStr] forKey:@"remindDate"];   ///提醒日期 yyyy-MM-dd HH:mm:ss
        [dic setValue:self.releaseContentTextView.text forKey:@"topicContext"];   //动态的内容详情
    }else if (self.sendType == KSendMoodDiary){
        [dic setValue:@"2" forKey:@"topicType"];    //心情日记2
        [dic setValue:self.releaseContentTextView.text forKey:@"topicContext"];   //动态的内容详情
    }else if (self.sendType == KSendHomeWork){ //作业
        
        if ([self.courseId isEqualToString:@"0"]) {//课后作业
            urlStr = [JSPathUtil urlAppFriendAddTopic];
            [dic setObject:@"4" forKey:@"topicType"];
            [dic setValue:self.releaseContentTextView.text forKey:@"topicContext"];   //动态的内容详情
        }else{//课堂作业
            urlStr = [JSPathUtil urlAppCourseAddHomework];
            [dic setObject:self.courseId forKey:@"courseId"];
            [dic setValue:self.releaseContentTextView.text forKey:@"context"];   //动态的内容详情
        }
        
    }
    
    MBProgressHUD *hud=[MBProgressHUD showProgress:@"loading..."];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [self.imageDataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *fileName = [NSString stringWithFormat:@"%@.jpeg", [Global timeStamp]];
            NSData *data = UIImageJPEGRepresentation(obj, 1.0f);
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        }];
    } error:nil];
    
    AFURLSessionManager *manager=[[AFURLSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      [hud hideAnimated:YES];
                      self.isSending = NO;
                      if (error) {
                          MyLog(@"Error: %@", error);
                      } else {
                          MyLog(@"%@ %@", response, responseObject);
                          NSError *err;
                          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject
                                                                              options:NSJSONReadingMutableContainers
                                                                                error:&err];
                          NSString *str = [NSString stringWithFormat:@"%@",dic[@"code"]];
                          if ([str isEqualToString:@"0"]) {
                              [Global showActivityWithView:self.view withText:[NSString stringWithFormat:@"发表%@成功",self.titleStr]];
                              [self.navigationController popViewControllerAnimated:YES];
                              if (self.sendFriendCircleBlock) {
                                  self.sendFriendCircleBlock();
                              }
                          }
                          else
                              [MBProgressHUD showMessage:dic[@"msg"]];

                          
                      }
                  }];
    
    [uploadTask resume];
}
#pragma mark - 更新学期目标
- (void)sendTermGoals{
    if (self.isSending) {
        return;
    }
    self.isSending = YES;
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:self.friendCircleId forKey:@"title"];   //必传 并且必须是 yyyy年上
    [dic setValue:self.releaseContentTextView.text forKey:@"context"];   //动态的内容详情
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppSummaryUpdateTermGoal] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            [Global showActivityWithView:self.view withText:@"设立成功"];
            if (self.sendFriendCircleBlock) {
                self.sendFriendCircleBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
        self.isSending = NO;
    }];
}
#pragma mark - 发给孩子
- (void)sendAdviceToParents{
    if (self.isSending) {
        return;
    }
    self.isSending = YES;
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:self.score forKey:@"value"];    //评分
    [dic setValue:[NSString stringWithFormat:@"%@-%@",[self.titleStr substringToIndex:4],[self.titleStr substringWithRange:NSMakeRange(5,2)]] forKey:@"date"];  //yyyy-MM
    [dic setValue:self.releaseContentTextView.text forKey:@"context"];   //动态的内容详情
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    [dic setValue:self.courseId forKey:@"child_id"];
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppInteractionAddParentSay] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            [Global showActivityWithView:self.view withText:@"发送成功"];
            if (self.sendFriendCircleBlock) {
                self.sendFriendCircleBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
        self.isSending = NO;
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
